package org.footballmanager.pandafootball.common.redis;

import org.footballmanager.pandafootball.common.exception.ExceptionEnum;
import org.footballmanager.pandafootball.common.exception.MyException;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * redis序列化对象
 *
 * @author chenjian
 * @since 2017年10月18日下午5:17:22
 */
public class RedisObjectSerializer implements RedisSerializer<Object> {
    private static final byte[] EMPTY_ARRAY = new byte[0];
    private Converter<Object, byte[]> serializer = new SerializingConverter();
    private Converter<byte[], Object> deserializer = new DeserializingConverter();

    /**
     * 反序列化
     *
     * @param bytes 参数
     * @return 返回值
     */
    public Object deserialize(byte[] bytes) {
        if (isEmpty(bytes)) {
            return null;
        }
        try {
            return deserializer.convert(bytes);
        } catch (Exception ex) {
            throw new MyException(ExceptionEnum.DESERIALIZEEXCEPTION, ex);
        }
    }

    /**
     * 序列化
     *
     * @param object 参数
     * @return 返回值
     */
    public byte[] serialize(Object object) {
        if (object == null) {
            return EMPTY_ARRAY;
        }
        return serializer.convert(object);
    }

    /**
     * 判空
     *
     * @param data 参数
     * @return 返回值
     */
    private boolean isEmpty(byte[] data) {
        return null == data || data.length == 0;
    }
}
